import React, { useEffect, useRef } from 'react';
import {
    Chart as ChartJS,
    CategoryScale, // ✅ 需要注册 category 轴，否则会报错
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend,
    Filler
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import styles from './lineChart.module.scss';

ChartJS.register(
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend,
    Filler
);

const LineChart = ({
    title = '数据统计',
    data = [],
    labels = []
}) => {
    const chartRef = useRef(null);

    useEffect(() => {
        return () => {
            if (chartRef.current) {
                chartRef.current.destroy();
            }
        };
    }, []);

    const options = {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            x: {
                type: 'category',
                grid: {
                    display: false
                }
            },
            y: {
                type: 'linear',
                beginAtZero: true,
                grid: {
                    color: 'rgba(0, 0, 0, 0.1)'
                }
            }
        },
        plugins: {
            legend: {
                position: 'top',
                labels: {
                    boxWidth: 20,
                    padding: 20,
                    font: {
                        size: 12
                    }
                }
            },
            title: {
                display: true,
                text: title,
                font: {
                    size: 16,
                    weight: 'bold'
                },
                padding: {
                    top: 10,
                    bottom: 20
                }
            }
        },
        interaction: {
            intersect: false,
            mode: 'index'
        },
        animation: {
            duration: 1000,
            easing: 'easeInOutQuart'
        }
    };

    const chartData = {
        labels: labels.length > 0 ? labels : ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00'],
        datasets: [
            {
                label: '数据',
                data: data.length > 0 ? data : [30, 40, 60, 70, 50, 80],
                borderColor: 'rgb(75, 192, 192)',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                borderWidth: 2,
                fill: true,
                tension: 0.4,
                pointRadius: 4,
                pointHoverRadius: 6,
                pointBackgroundColor: '#fff',
                pointBorderColor: 'rgb(75, 192, 192)',
                pointHoverBackgroundColor: 'rgb(75, 192, 192)',
                pointHoverBorderColor: '#fff'
            }
        ]
    };

    return (
        <div className={styles.chartContainer}>
            <Line ref={chartRef} options={options} data={chartData} />
        </div>
    );
};

export default LineChart;